package com.stu.wgt.test.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stu.wgt.test.bean.Shipment;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.service.ShipmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-02-04
 */
@RestController
@RequestMapping("/shipment")
public class ShipmentController {

    @Autowired
    ShipmentService shipmentService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public R addShipment(@RequestBody Shipment shipment) {
        int result = shipmentService.insert(shipment);
        if (result == 1) {
            return R.ok().data("msg", "添加成功");
        }
        return R.error().data("msg", "添加失败");
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public R deleteShipment(@PathVariable("id") Integer id) {
        int result = shipmentService.delete(id);
        if (result == 1) {
            return R.ok().data("msg", "删除成功");
        }
        return R.error().data("msg", "删除失败");

    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    public R updateShipment(@PathVariable("id") Integer id, @RequestBody Shipment shipment) {
        shipment.setId(id);
        int result = shipmentService.update(shipment);
        if (result == 1) {
            return R.ok().data("msg", "更新成功");
        }
        return R.error().data("msg", "更新失败");

    }

    @RequestMapping(value = "/selectById/{id}", method = RequestMethod.GET)
    public R selectById(@PathVariable("id") Integer id) {
        try {
            List<Shipment> shipmentList = shipmentService.selectById(id);
            return R.ok().data("shipment", shipmentList);
        } catch (Exception e) {
            return R.error().data("msg", "查询失败");
        }
    }

    @RequestMapping(value = "/selectBytrackNumber/{trackNumber}", method = RequestMethod.GET)
    public R selectByTrackNumber(@PathVariable("trackNumber") String trackNumber) {
        try {
            List<Shipment> shipmentList = shipmentService.selectByTrackNumber(trackNumber);
            return R.ok().data("shipment", shipmentList);
        } catch (Exception e) {
            return R.error().data("msg", "查询失败");
        }
    }

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public R searchShipment(
            @RequestParam("query") String query,
            @RequestParam("pagenum") Integer pageNum,
            @RequestParam("pagesize") Integer pageSize
    ) {
        try {
            IPage<Shipment> shipmentIPage = shipmentService.searchShipment(query, pageNum, pageSize);
            return R.ok().data("shipment", shipmentIPage.getRecords()).data("total", shipmentIPage.getTotal());
        } catch (Exception e) {
            return R.error().data("msg", "查询失败");
        }
    }

}

